<template>
    <div style="padding-left:20px;">
        <!-- 搜索栏 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item label="产品名称" prop="productName">
                <el-input 
                    v-model="queryParams.productName" 
                    placeholder="请输入产品名称" 
                    clearable 
                    size="small" 
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备类型" prop="deviceType">
                <el-select 
                    v-model="queryParams.deviceType" 
                    placeholder="请选择类型" 
                    clearable 
                    size="small"
                >
                    <el-option 
                        v-for="dict in dict.type.iot_device_type" 
                        :key="dict.value" 
                        :label="dict.label" 
                        :value="parseInt(dict.value)"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    
        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button 
                    type="primary" 
                    plain 
                    icon="el-icon-plus" 
                    size="mini" 
                    @click="handleAdd" 
                    v-hasPermi="['iot:product:bind']"
                >绑定子产品</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button 
                    type="danger" 
                    plain 
                    icon="el-icon-delete" 
                    size="mini" 
                    :disabled="multiple" 
                    @click="handleBatchUnbind"
                    v-hasPermi="['iot:product:unbind']"
                >批量解绑</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-link type="info" style="padding-top:5px" :underline="false">双击行查看子产品详情</el-link>
            </el-col>
        </el-row>
    
        <!-- 数据表格 -->
        <el-table 
            v-loading="loading" 
            :data="subProducts" 
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowDblClick"
            size="small"
            border
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="产品ID" prop="productId" align="center" width="120" />
            <el-table-column label="产品名称" prop="productName" align="center" />
            <el-table-column label="设备类型" prop="deviceType" align="center" width="500">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.iot_device_type" :value="scope.row.deviceType" />
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" align="center" width="560">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="420" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button 
                        size="mini" 
                        type="text" 
                        icon="el-icon-delete" 
                        @click="handleUnbind(scope.row)"
                        v-hasPermi="['iot:product:unbind']"
                    >解绑</el-button>
                </template>
            </el-table-column>
        </el-table>
    
        <!-- 分页 -->
        <pagination 
            v-show="total>0" 
            :total="total" 
            :page.sync="queryParams.pageNum" 
            :limit.sync="queryParams.pageSize" 
            @pagination="getList"
        />
    
        <!-- 子产品选择对话框 -->
        <el-dialog title="选择子产品" :visible.sync="selectDialogVisible" width="80%">
            <div class="dialog-container">
                <!-- 搜索栏 -->
                <el-form :inline="true" class="search-form">
                    <el-form-item label="产品名称">
                        <el-input 
                            v-model="selectQuery.productName" 
                            placeholder="请输入产品名称" 
                            clearable 
                            size="small"
                            @keyup.enter.native="handleSelectQuery"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSelectQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetSelectQuery">重置</el-button>
                    </el-form-item>
                </el-form>
    
                <!-- 可选产品列表 -->
                <el-table 
                    ref="selectTable"
                    v-loading="selectLoading"
                    :data="selectList"
                    @selection-change="handleSelectChange"
                    border
                    size="small"
                >
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="产品ID" prop="productId" align="center" width="90" />
                    <el-table-column label="产品名称" prop="productName" align="center" />
                    <el-table-column label="设备类型" prop="deviceType" align="center" width="100">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.iot_device_type" :value="scope.row.deviceType" />
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="createTime" align="center" width="160">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
                        </template>
                    </el-table-column>
                </el-table>
    
                <!-- 分页 -->
                <pagination 
                    v-show="selectTotal>0" 
                    :total="selectTotal" 
                    :page.sync="selectQuery.pageNum" 
                    :limit.sync="selectQuery.pageSize" 
                    @pagination="getSelectList"
                />
            </div>
    
            <div slot="footer" class="dialog-footer">
                <el-button @click="selectDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleBindConfirm">确 定</el-button>
            </div>
        </el-dialog>
    
        <!-- 子产品详情对话框 -->
        <el-dialog title="子产品详情" :visible.sync="detailDialogVisible" width="600px">
        <el-descriptions border :column="2" size="medium" v-if="currentProduct">
            <el-descriptions-item label="产品ID">{{ currentProduct.productId }}</el-descriptions-item>
            <el-descriptions-item label="产品名称">{{ currentProduct.productName }}</el-descriptions-item>
            <el-descriptions-item label="设备类型">
            <dict-tag :options="dict.type.iot_device_type" :value="currentProduct.deviceType"/>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentProduct.createTime }}</el-descriptions-item>
        </el-descriptions>
        <div v-else style="text-align:center;color:#909399;">
            <i class="el-icon-warning"></i> 未找到产品信息
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关 闭</el-button>
        </div>
        </el-dialog>
    </div>
    </template>
    
    <script>
    import { listBoundSubs, bindSubs, unbindSub, batchUnbindSubs } from "@/api/iot/product";
    import { listAvailableSubs } from "@/api/iot/product";
    // import ProductDetailPreview from "@/views/iot/product/product-detail-preview";
    
    export default {
        name: "ProductSubManage",
        dicts: ['iot_device_type'],
        props: {
            productId: {
                type: Number,
                required: true
            },
            deviceType: {
                type: Number,
                default: 1
            }
        },
        data() {
            return {
                // 主数据
                loading: true,
                subProducts: [],
                total: 0,
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    productName: undefined,
                    deviceType: 4 // 网关子设备
                },
                // 选择对话框数据
                selectDialogVisible: false,
                selectLoading: false,
                selectList: [],
                selectTotal: 0,
                selectQuery: {
                    pageNum: 1,
                    pageSize: 10,
                    productName: undefined
                },
                // 选中数据
                selectedIds: [],
                selectedSubs: [],
                // 详情对话框
                detailDialogVisible: false,
                currentProduct: null,
                // 其他
                showSearch: true,
                multiple: true
            };
        },
        watch: {
            productId: {
                immediate: true,
                handler(newVal) {
                    if (newVal) this.getList();
                }
            }
        },
        methods: {
            /** 获取已绑定子产品 */
            getList() {
                this.loading = true;
                this.queryParams.productId=this.productId
                listBoundSubs(this.queryParams).then(response => {
                    this.subProducts = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            /** 打开选择对话框 */
            handleAdd() {
                this.selectDialogVisible = true;
               
                this.selectQuery.deviceType=4
                this.getSelectList();
            },
            /** 获取可选子产品 */
            getSelectList() {
                this.selectLoading = true;
               
                listAvailableSubs(this.selectQuery).then(response => {
                    // 过滤已绑定的产品
                    this.selectList = response.rows.filter(item => 
                        !this.subProducts.some(sub => sub.productId === item.productId)
                    );
                    this.selectTotal = response.total;
                    this.selectLoading = false;
                });
            },
            /** 确认绑定 */
            handleBindConfirm() {
                if (this.selectedSubs.length === 0) {
                    this.$modal.msgWarning("请至少选择一个子产品");
                    return;
                }
                
                const subproductIds = this.selectedSubs.map(item => item.productId);
                console.log(subproductIds);
                bindSubs(this.productId, subproductIds).then(() => {
                    this.$modal.msgSuccess("绑定成功");
                    this.getList();
                    this.selectDialogVisible = false;
                });
            },
            /** 单个解绑 */
            handleUnbind(row) {
                this.$confirm(`确认解绑子产品【${row.productName}】?`, "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    return unbindSub(this.productId, row.productId);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("解绑成功");
                });
            },
            /** 批量解绑 */
            handleBatchUnbind() {
                if (this.selectedIds.length === 0) {
                    this.$modal.msgWarning("请至少选择一条数据");
                    return;
                }
                
                this.$confirm("确认批量解绑选中的数据吗?", "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    return batchUnbindSubs(this.productId, this.selectedIds);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("解绑成功");
                });
            },
            /** 表格选择变化 */
            handleSelectionChange(selection) {
                this.selectedIds = selection.map(item => item.productId);
                this.multiple = !selection.length;
            },
            /** 选择对话框选择变化 */
            handleSelectChange(selection) {
                this.selectedSubs = selection;
            },
            /** 行双击事件 */
            handleRowDblClick(row) {
                this.currentProduct = row;
                this.detailDialogVisible = true;
            },
            /** 搜索 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置查询 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 选择对话框搜索 */
            handleSelectQuery() {
                this.selectQuery.pageNum = 1;
                this.getSelectList();
            },
            /** 重置选择对话框查询 */
            resetSelectQuery() {
                this.selectQuery = {
                    pageNum: 1,
                    pageSize: 10,
                    productName: undefined
                };
                this.getSelectList();
            }
        }
    };
    </script>
    
    <style scoped>
    .dialog-container {
        padding: 20px;
        background: #fff;
    }
    .search-form {
        margin-bottom: 15px;
    }
    </style>